import tkinter as tk
from tkinter import ttk


class TipEntry(ttk.Entry):
    def __init__(self, master, init_text, tip_text, *args, **kwargs):
        self.style = ttk.Style()
        self.style_name = tip_text + ".TEntry"
        self.style.configure(
            self.style_name,  # 样式名称（可自定义）
            foreground="#999999"  # 灰色（十六进制或颜色名）
        )
        super().__init__(master, *args, **kwargs, style=self.style_name)
        self.text = init_text if init_text else tip_text  # 提示文本
        self.tip_text = tip_text
        self.insert(0, self.text)

        if init_text == tip_text:
            self.style.configure(self.style_name, foreground="#999999")
        else:
            self.style.configure(self.style_name, foreground="#000000")

        # 绑定焦点事件
        self.bind("<FocusIn>", self.on_focus_in)
        self.bind("<FocusOut>", self.on_focus_out)

    def on_focus_in(self, event):
        if self.tip_text == self.get():
            self.delete(0, tk.END)
            self.style.configure(self.style_name, foreground="#000000")

    def on_focus_out(self, event):
        if not self.get():
            self._show_tip()
        elif self.tip_text == self.get():
            self.style.configure(self.style_name, foreground="#000000")
        else:
            self.style.configure(self.style_name, foreground="#000000")

    def _show_tip(self):
        """显示提示文本（灰色）"""
        # 先删除可能存在的提示（避免重复）
        self.delete(0, tk.END)
        # 插入提示文本
        self.insert(0, self.tip_text)
        self.style.configure(self.style_name, foreground="#999999")
